﻿using System;
using System.Web.Configuration;
using System.Web.UI.WebControls;
using eCommerce.core;
using eCommerce.core.Helpers;
using eCommerce.db;
using eCommerce.db.BORespository;

namespace eCommerce.web.Controls.Article
{
    public partial class List : System.Web.UI.UserControl
    {
        public string CategoryName { get; set; }

        public int CategoryId { get; set; }
        protected int PageIndex;
        protected int PageSize;  

        protected void Page_Load(object sender, EventArgs e)
        {                        
            PageIndex = Utils.GetIdFromRequestString(Utils.PageIndex, Constant.PageIndex);
            PageSize  = Utils.GetIdFromRequestString(Utils.PageSize, Constant.SmallPageSize);

            if (!IsPostBack)
                ListPagingArticle();
        }

        private void ListPagingArticle()
        {            
            var totalRecords = 0;
            var lstArticle   = ArticleBo.GetListPagination(CategoryId, PageIndex, PageSize, ref totalRecords);
            var categoryName = CategoryId > 0 ? Utils.UnsignAndDash(CategoryBo.GetCategoryName(CategoryId)) : "tin-tuc";
            
            if (lstArticle.Count > 0)
            {
                rptArticle.DataSource = lstArticle;
                rptArticle.DataBind();

                ltPager.Text = PagerHelper.PageLinks(PageIndex, PageSize, 100, Constant.PageStep,
                                    UrlHelper.ListPaginationArticleByCategory(categoryName, "{0}"));                
            }
        }

        protected void rptArticle_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                var articleId   = Utils.ToInt32(((HiddenField)e.Item.FindControl("hfArticleId")).Value);
                var categoryUrl = ((HiddenField)e.Item.FindControl("hfCategoryUrl")).Value;
                var articleUrl  = ((HiddenField)e.Item.FindControl("hfArticleUrl")).Value;
                var imgAvatar = ((HiddenField)e.Item.FindControl("hfImgAvatar")).Value;
                
                var ltImage = (Literal)e.Item.FindControl("ltImage");
                var imgHref = string.Format(Constant.ThumbImage, WebConfigurationManager.AppSettings["Thumbnail"], imgAvatar, (int)SettingType.Article, 280);

                ltImage.Text = string.Format("<a href=\"{0}\">{1}</a>", UrlHelper.ArticleDetail(categoryUrl, articleId, articleUrl), imgHref);
            }
        }
    }
}